package com.xqx.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author：xingquanxiang createTime：2019/11/27 15:29
 * description:
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("------全局过滤器MyGlobalFilter--------");
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        //判断token是否为空白
        if (StringUtils.isBlank(token)){
            //设置未经授权状态码 401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 放行
            return exchange.getResponse().setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //值越小越先执行
        return 1;
    }
}
